package org.wu.reggie.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.wu.reggie.entity.ShoppingCart;
import org.wu.reggie.mapper.ShoppingCartMapper;
import org.wu.reggie.service.ShoppingCartService;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {


    @Autowired
    private ShoppingCartMapper shoppingCartMapper;


    // 根据用户id查看购物车
    @Override
    public List<ShoppingCart> findCartByUserId(Long userId) {

        List<ShoppingCart> shoppingCartList =  shoppingCartMapper.findCartByUserId(userId);

        return shoppingCartList;
    }

    /**
     * 作用 添加购物车
     * @param shoppingCart 当前提交的购物项数据
     * @return
     */
    @Override
    public ShoppingCart add(ShoppingCart shoppingCart) {

        // 1 根据用户的id与dish_id 或者setmeal_id 查看
        ShoppingCart shoppingCartOne = shoppingCartMapper.findUidAndDidOrSid(shoppingCart);

        // 2 如果查询为空 插入一条新的记录
        if (shoppingCartOne == null){
            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartMapper.save(shoppingCart);
            shoppingCartOne = shoppingCart;
        }else {
            // 3 如果不为空 数量就+1
            shoppingCartOne.setNumber(shoppingCartOne.getNumber() + 1);
            shoppingCartMapper.update(shoppingCartOne);
        }
        return shoppingCartOne;
    }


    /**
     * 清空购物车
     * @param userId
     */
    @Override
    public void clean(Long userId) {
        shoppingCartMapper.clean(userId);
    }
}
